<template>
    <div class="flex_col_start bk3 h100">
        <!-- <div class="flex_row_center mt5 w100" style="justify-content: center;">
            <label class="f2">正方:</label>
            <label class="ml5 f2">{{ ctx.pos }}</label>
        </div>
        <div class="flex_row_center mt5 w100" style="justify-content: center;">
            <label class="f2">反方:</label>
            <label class="ml5 f2">{{ ctx.neg }}</label>
        </div> -->
        <div class="w100" style="min-height: 45%; font-size: 35px; text-align: center;">第{{ ctx.vote_id }}阶段</div>

        <Bar :data="chartData" :options="chartOptions" class="w100" style="min-height: 45%; max-height: 45%;" />

        <div class="flex_row w100" style="justify-content: space-around;">
            <el-button @click="onClickPos" type="primary">支持正方</el-button>
            <el-button @click="onClickNeg" type="primary">支持反方</el-button>
        </div>

    </div>
</template>

<script lang="ts" setup>
import { current_id, get_vote_count, updateFlag, vote, VOTE_NEG, VOTE_POS } from '@/service/api';
import { run } from '@/utils/ui';
import { reactive, ref, watch } from 'vue';
import { chartOptions } from '@/service/const';
import { Bar } from 'vue-chartjs';

const chartData = ref({
    labels: ['正方', '反方'],
    datasets: [
        {
            label: '正方票数',
            data: [0],
            backgroundColor: ['red'],
        },
    ],
});

interface Ctx {
    pos: number,
    neg: number,
    vote_id: number,
}

const ctx = reactive<Ctx>({
    pos: 0,
    neg: 0,
    vote_id: 0,
});

async function init() {
    await run(async () => {
        const pos = await get_vote_count(VOTE_POS);
        const neg = await get_vote_count(VOTE_NEG);
        const vote_id = await current_id();
        ctx.pos = pos;
        ctx.neg = neg;
        ctx.vote_id = vote_id;
        chartData.value = {
            labels: ['正方', '反方'],
            datasets: [
                {
                    label: '',
                    data: [pos, neg],
                    backgroundColor: ['red', 'blue'],
                },
            ],
        }
    });
}

async function onClickPos() {
    await run(async () => {
        await vote(VOTE_POS);
    });
    await init();
}

async function onClickNeg() {
    await run(async () => {
        await vote(VOTE_NEG);
    });
    await init();
}

init();

watch(updateFlag, () => {
    init();
})

</script>
